package com.ky.home.controller;


import cn.hutool.core.convert.NumberWithFormat;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ky.common.config.SystemConfig;
import com.ky.common.util.JwtUtil;
import com.ky.common.vo.R;
import com.ky.home.entity.StudyTime;
import com.ky.home.mapper.StudyTimeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author pl
 * @since 2024-06-24
 */
@RestController
@RequestMapping("/home/study-time")
public class StudyTimeController {
    @Autowired
    StudyTimeMapper studyTimeMapper;
    @RequestMapping("/updateStudyTime/{studyTime}")
    R updateStudyTime(HttpServletRequest request, @PathVariable("studyTime") int studyTime){
        String token = request.getHeader(SystemConfig.HEADER_TOKEN);
        Integer id = ((NumberWithFormat) JwtUtil.parseToken(token, "id")).intValue();
        QueryWrapper<StudyTime> studyTimeQueryWrapper = new QueryWrapper<>();
        studyTimeQueryWrapper.eq("user_id",id);
        StudyTime studyTime1 = studyTimeMapper.selectOne(studyTimeQueryWrapper);
        if(studyTime1==null){
            studyTimeMapper.insert(new StudyTime().setUserId(id).setTime(studyTime).setTodayTime(studyTime));
            return R.ok();
        }
        studyTime1.setTodayTime(studyTime);
        studyTime1.setTime(studyTime1.getTime()+studyTime);
        studyTimeMapper.updateById(studyTime1);
        return R.ok();
    }
    @RequestMapping("/getStudyTime")
    public R getStudyTime(HttpServletRequest request){
        String token = request.getHeader(SystemConfig.HEADER_TOKEN);
        Integer id = ((NumberWithFormat) JwtUtil.parseToken(token, "id")).intValue();
        QueryWrapper<StudyTime> studyTimeQueryWrapper = new QueryWrapper<>();
        studyTimeQueryWrapper.eq("user_id",id);
        StudyTime studyTime1 = studyTimeMapper.selectOne(studyTimeQueryWrapper);
        return R.ok(studyTime1);
   }
}

